package com.dzpk.gameserver.net;

import com.dzpk.gameserver.action.CommandEnum;
import com.dzpk.gameserver.protocol.MessageStruct;
import com.dzpk.gameserver.util.BeanControler;
import com.dzpk.gameserver.util.Broadcaster;
import com.dzpk.gameserver.util.CommonPackageUtil;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import somnus.net.SocketServer;

public class GameServer extends SocketServer {

    private void noticeClientShutdown() {
        log.info("notice clients that the server will shutdown!");
        int delay = BeanControler.getSystemConfig().getShutdownDelay();
        int interval = BeanControler.getSystemConfig().getShutdownInterval();
        if (delay > 0) {
            while (true) {
                if (delay <= 0) {
                    break;
                }

                IoBuffer message = CommonPackageUtil.getDataPackage(CommandEnum.S2C_SERVER_WILL_SHUTDOWN_RESP,
                        MessageStruct.PBInt.newBuilder().setValue(delay).build().toByteArray());
                Broadcaster.broadcastPlayerAll(message);

                int sleep = interval;
                if (delay < interval) {
                    sleep = delay;
                }
                try {
                    Thread.sleep(sleep * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                delay -= interval;
            }
        }

        log.info("notice cliens  end!");
    }

    @Override
    public void afterShutdown() {
        super.afterShutdown();
        closeAllClient();
    }

    @Override
    public void beforeShutdown() {
        super.beforeShutdown();
        noticeClientShutdown();
    }

    private void closeAllClient() {
        log.info("close all client socket!");
        for (IoSession s : BeanControler.getGameServer().getSessions().values()) {
            if (s != null) {
                s.close(true);
            }
        }
        log.info("close all client end!");
    }

}
